﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using ZBZH_Manage_Order.Models;
using ZBZH_Manage_Order.PublicMethod;
using Model;

namespace ZBZH_Manage_Order.Controllers.UserManagement
{
    /// <summary>
    /// 用户商户积分管理
    /// </summary>
    public class UserMerchantsManageController : BaseController
    {
        // 保存模型数据
        private static
            Dictionary<string, Model.View_Order_UserInt> modelDic = new Dictionary<string, Model.View_Order_UserInt>();
        private static
            List<Model.View_Order_UserInt> modelList = new List<Model.View_Order_UserInt>();
        // 操作员
        protected Model.View_OperUser operUser;

        // 加载商户
        public ActionResult InitMerID(JqGridParam jqgridparam)
        {
            try
            {
                Page<Model.Order_Mer_T> page = new Page<Model.Order_Mer_T>();
                List<Model.Order_Mer_T> list = new List<Model.Order_Mer_T>();//定义商品分类设置
                Model.View_OperUser user = (Model.View_OperUser)Session[SessionStorage.OperUser];

                if (user == null)
                {
                    return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                }

                string result = SRS.GetMer(user.OperID, "", 1);
                JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                if (bs == "1")//返回结果正常
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    if (jieguo.Count > 0)
                    {
                        foreach (JToken item in jieguo)
                        {
                            Model.Order_Mer_T m = new Model.Order_Mer_T();
                            m.MerID = item["MerID"].ToString();
                            m.MerName = item["MerName"].ToString();
                            m.MerAdr = item["MerAdr"].ToString();
                            m.MerCall = item["MerCall"].ToString();
                            m.MerTxt = item["MerTxt"].ToString();
                            list.Add(m);
                        }
                    }
                    jqgridparam.records = list.Count;//查询的数据总数
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = page.FindListPage(list, ref jqgridparam)//返回当前页的数据
                    };
                    return Json(data);
                }
                return Json(searcho["Msg"].ToString());
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }

        /// <summary>
        /// 查询所有用户平台积分信息
        /// </summary>
        /// <returns></returns>
        //public List<Model.View_Order_UserInt> GetGridData(string MerID)
        //{
        //    #region 加载表格
        //    List<Model.View_Order_UserInt> list_UserInt = new List<Model.View_Order_UserInt>();
        //    string result = SRS.GetOrder_UserInt(MerID, YZM, 1);  // 执行远程请求
        //    if (!string.IsNullOrEmpty(result) && result.IndexOf("\"BS\":\"1\"") > -1)
        //    {
        //        JObject search = JObject.Parse(result);//将服务返回的结果进行优化
        //        string bsMer = search["BS"].ToString();//获取返回结果是否正常标识
        //        if (bsMer == "1")//返回结果正常
        //        {
        //            IList<JToken> jieguoMer = search["rows"].Children().ToList();//解析返回的结果
        //            if (jieguoMer.Count > 0)
        //            {
        //                foreach (JToken item in jieguoMer)
        //                {
        //                    Model.View_Order_UserInt m = new Model.View_Order_UserInt();
        //                    m.UserIntID = int.Parse(item["UserIntID"].ToString());
        //                    m.AccID = int.Parse(item["AccID"].ToString());
        //                    m.IntID = item["IntID"].ToString();
        //                    m.IntNowNub = int.Parse(item["IntNowNub"].ToString());
        //                    m.IntAllNub = int.Parse(item["IntAllNub"].ToString());
        //                    m.IntConNub = int.Parse(item["IntConNub"].ToString());
        //                    m.IntNowNub = int.Parse(item["IntNowNub"].ToString());
        //                    m.IntNowNub = int.Parse(item["IntNowNub"].ToString());
        //                    m.LastUpTime = item["LastUpTime"].ToString();
        //                    m.LastUpFlow = item["LastUpFlow"].ToString();
        //                    m.BZ = item["BZ"].ToString();
        //                    m.AccNum = item["AccNum"].ToString();
        //                    m.AccCall = item["AccCall"].ToString();
        //                    m.AccName = item["AccName"].ToString();
        //                    m.AccIdentifier = item["AccIdentifier"].ToString();
        //                    m.AccSex = int.Parse(item["AccSex"].ToString());
        //                    m.AccCerType = item["AccCerType"].ToString();
        //                    m.AccCerNub = item["AccCerNub"].ToString();
        //                    m.IdentityID = item["IdentityID"].ToString();
        //                    m.CategoryID = item["CategoryID"].ToString();
        //                    m.SataeID = item["SataeID"].ToString();
        //                    m.AccCerType_DicName_Login = item["AccCerType_DicName_Login"].ToString();
        //                    m.DepID = item["DepID"].ToString();
        //                    m.DepID_DepName_Department = item["DepID_DepName_Department"].ToString();
        //                    m.IdentityID_DiName_SystemIdentity = item["IdentityID_DiName_SystemIdentity"].ToString();
        //                    m.CategoryID_DicName_SystemIdentity = item["CategoryID_DicName_SystemIdentity"].ToString();
        //                    m.StateID_DicName_SystemIdentity = item["StateID_DicName_SystemIdentity"].ToString();
        //                    m.MerID = item["MerID"].ToString();
        //                    list_UserInt.Add(m);
        //                }
        //            }
        //        }
        //    }
        //    return list_UserInt;
        //    #endregion
        //}

        /// <summary>
        /// 查询对应商户的用户积分
        /// </summary>
        /// <param name="MerID">商户ID</param>
        /// <param name="jqgridparam">分页参数</param>
        /// <returns></returns>
        public ActionResult InitTable(string MerID, JqGridParam jqgridparam)
        {
            #region 加载表格
            try
            {
                List<Model.View_Order_UserInt> list_UserWalt = new List<Model.View_Order_UserInt>();
                Dictionary<string, string> Dic = new Dictionary<string, string>();
                string result = SRS.GetOrder_UserInt(jqgridparam.page, jqgridparam.rows, MerID, Dic, YZM, 1);  // 执行远程请求
                JObject searcho = JObject.Parse(result);
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    list_UserWalt = ParseClass<Model.View_Order_UserInt>.JsonList(jieguo);//解析返回的结果\
                    //List<Model.Order_Organization_T> newList = new List<Order_Organization_T>();
                    //foreach (Model.Order_Organization_T item in List)
                    //{
                    //    int a = item.OrgWaltLimit / 100;
                    //    item.OrgWaltLimit = a;
                    //    int b = item.OrgWaltBalance/100;
                    //    item.OrgWaltBalance = b;
                    //    newList.Add(item);
                    //    //int newimit = int.Parsitem.OrgWaltLimit.ToString());
                    //}
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list_UserWalt
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = list_UserWalt
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
            //Page<Model.View_Order_UserInt> page = new Page<Model.View_Order_UserInt>();
            //List<Model.View_Order_UserInt> list_UserWalt = new List<Model.View_Order_UserInt>();
            //list_UserWalt = GetGridData(MerID);
            //jqgridparam.records = list_UserWalt.Count;//查询的数据总数
            //var data = new
            //{
            //    total = list_UserWalt.Count,
            //    rows = page.FindListPage(list_UserWalt, ref jqgridparam)//返回当前页的数据
            //};
            //return Json(data);
            #endregion
        }

        /// <summary>
        /// 查询用户商户积分信息
        /// </summary>
        /// /// <param name="MerID">商户ID</param>
        /// <param name="SearchAccName">姓名</param>
        /// <param name="SearchAccCall">手机号</param>
        /// <param name="SearchAccIdentifier">个人编号</param>
        /// <param name="SearchAccCerNub">证件号</param>
        /// <param name="SearchDepID">组织结构ID</param>
        /// <param name="jqgridparam">分页参数</param>
        /// <returns></returns>
        public ActionResult SeachTable(string MerID,string SearchAccName, string SearchAccCall, string SearchAccIdentifier, string SearchAccCerNub, string SearchDepID, JqGridParam jqgridparam)
        {
            #region 加载表格
            try
            {
                // 声明实体
                List<Model.View_Order_UserInt> List = new List<View_Order_UserInt>();
                Dictionary<string, string> Dic = new Dictionary<string, string>();
                Dic.Add("AccName", SearchAccName);
                Dic.Add("AccCall", SearchAccCall);
                Dic.Add("AccIdentifier", SearchAccIdentifier);
                Dic.Add("AccCerNub", SearchAccCerNub);
                Dic.Add("DepID", SearchDepID);
                // 调用服务接口
                string result = SRS.GetOrder_UserInt(jqgridparam.page, jqgridparam.rows, MerID, Dic, YZM, 1);
                // 将服务返回的结果进行优化
                JObject searcho = JObject.Parse(result);
                string bs = searcho["BS"].ToString();
                if (bs == "1")
                {
                    IList<JToken> jieguo = searcho["rows"].Children().ToList();//解析返回的结果
                    List = ParseClass<Model.View_Order_UserInt>.JsonList(jieguo);//解析返回的结果\
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = List
                    };
                    return Json(data);
                }
                else
                {
                    var data = new
                    {
                        total = searcho["total"].ToString(),
                        rows = List
                    };
                    return Json(data);
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
            //Page<Model.View_Order_UserInt> page = new Page<Model.View_Order_UserInt>();
            //List<Model.View_Order_UserInt> list_UserInt = new List<Model.View_Order_UserInt>();
            ////list_UserInt = GetGridData(MerID);
            ////姓名
            //if (SearchAccName != "")
            //{
            //    list_UserInt = list_UserInt.Where(i => i.AccName.IndexOf(SearchAccName) > -1).ToList();
            //}
            ////电话号
            //if (SearchAccCall != "")
            //{
            //    list_UserInt = list_UserInt.Where(i => i.AccCall.IndexOf(SearchAccCall) > -1).ToList();
            //}
            ////个人编号
            //if (SearchAccIdentifier != "")
            //{
            //    list_UserInt = list_UserInt.Where(i => i.AccIdentifier.IndexOf(SearchAccIdentifier) > -1).ToList();
            //}
            ////证件号
            //if (SearchAccCerNub != "")
            //{
            //    list_UserInt = list_UserInt.Where(i => i.AccCerNub.IndexOf(SearchAccCerNub) > -1).ToList();
            //}
            ////部门ID
            //if (SearchDepID != "")
            //{
            //    list_UserInt = list_UserInt.Where(i => i.DepID == SearchDepID).ToList();
            //}
            //jqgridparam.records = list_UserInt.Count;//查询的数据总数
            //var data = new
            //{
            //    total = list_UserInt.Count,
            //    rows = page.FindListPage(list_UserInt, ref jqgridparam)//返回当前页的数据
            //};
            //return Json(data);
            #endregion
        }

        /// <summary>
        /// 保存商户积分变更
        /// </summary>
        /// <param name="model">积分变更参数</param>
        /// <returns></returns>
        public ActionResult BtnEdit(UpDateUserInt model)
        {
            #region 积分编辑

            // 获取操作员
            operUser = Session[SessionStorage.OperUser] as Model.View_OperUser;
            if (operUser != null)
            {
                try
                {
                    string result = SRS.SetOrder_UserInt(operUser.OperID, model.UserIntID, "1B0003", "", model.updateInt, model.BZ, "", 1);//从接口获得所有流水
                    JObject searcho = JObject.Parse(result);//将服务返回的结果进行优化
                    string bs = searcho["BS"].ToString();//获取返回结果是否正常标识
                    if (bs == "1")//返回结果正常
                    {
                        return Json(bs);
                    }
                    else
                    {
                        return Json(searcho["MSG"].ToString());
                    }
                }
                catch (Exception e)
                {
                    string error = e.Message;
                    return Json(error);
                }
            }
            else
            {
                //return Json("获取操作员出错！");           
                return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面
                
            }
            #endregion
        }

        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public ActionResult getDep()
        {
            ZHHQSERVICE.Service1Client service = new ZHHQSERVICE.Service1Client();
            try
            {
                Model.View_OperUser operUser = Session[SessionStorage.UserLogin] as Model.View_OperUser;
                List<TreeJsonEntity> TreeList = new List<TreeJsonEntity>();
                string result = service.GetDepatMentNoValidate("", 1);
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                List<ZBZH_Manage_Order.Models.Basic_Department_T> ls = new List<ZBZH_Manage_Order.Models.Basic_Department_T>();
                JObject jb = JObject.Parse(result);
                if (jb["BS"].ToString() == "1")//返回结果正常
                {
                    IList<JToken> jieguo = jb["rows"].Children().ToList();
                    ls = ParseClass<ZBZH_Manage_Order.Models.Basic_Department_T>.JsonList(jieguo);//解析返回的结果
                    foreach (ZBZH_Manage_Order.Models.Basic_Department_T item in ls)
                    {
                        bool hasChildren = false;
                        IList childnode = ls.FindAll(t => t.DepParentID == item.DepID);
                        if (childnode.Count > 0)
                        {
                            hasChildren = true;
                        }
                        TreeJsonEntity tree = new TreeJsonEntity();
                        tree.id = item.DepID;
                        tree.text = item.DepName;
                        tree.value = item.DepID;
                        tree.isexpand = true;
                        tree.complete = true;
                        tree.hasChildren = hasChildren;
                        tree.parentId = item.DepParentID;
                        TreeList.Add(tree);
                    }
                    string a = TreeList.TreeToJson();
                    return Content(TreeList.TreeToJson());
                }
                else
                {
                    return Json(jb["Msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                return Json("操作异常：" + ex + "请联系管理员解决");
            }
        }
        // 主页
        public ActionResult Index()
        {
            operUser = Session[SessionStorage.OperUser] as Model.View_OperUser;
            if (operUser != null)
            {
                ViewBag.UserPowers = operUser.RolePower;
                // 身份类型
                ViewBag.AccCerTypeList = GetDicForDictID("18");
                // 部门
                List<SelectListItem> slis = new List<SelectListItem>();
                foreach (ZBZH_Manage_Order.Models.Basic_Department_T m in GetDepList(operUser))
                {
                    SelectListItem sli = new SelectListItem();
                    sli.Text = m.DepName;
                    sli.Value = m.DepID;
                    slis.Add(sli);
                }
                ViewBag.DepIDList = slis;
            }
            else
            {      
               return RedirectToAction("LoginPage", "Login");  //czx:修改为登录者的Session异常时，直接跳转到登录页面           
            }

            return View();
        }

        #region 定义实体类
        /// <summary>
        /// 更新用户积分信息实体类
        /// </summary>
        public class UpDateUserInt
        {
            public int UserIntID { get; set; }
            public int updateInt { get; set; }
            public string BZ { get; set; }
        }
        #endregion

    }
}
